package com.icarsaas.saas.tenant.cars.customer.service;

import com.icarsaas.saas.common.page.SoulPage;
import com.icarsaas.saas.tenant.cars.customer.model.Store;
import com.icarsaas.saas.tenant.cars.customer.repository.StoreRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class StoreService {
	@Autowired private StoreRepository storeRepository;
	
	public Store get(String id) {
		return storeRepository.findById(id).orElse(null);
	}

	public List<Store> findAll() {
		return storeRepository.findAll();
	}

	@Transactional(readOnly = false, value = "tenantTransactionManager")
	public Store save(Store entity) {
		return storeRepository.save(entity);
	}

	@Transactional(readOnly = false, value = "tenantTransactionManager")
	public void delete(String id) {
		storeRepository.deleteById(id);
	}

	public SoulPage<Map<String, Object>> listSoulData(SoulPage<Map<String, Object>> page, Map<String, Object> params) {
		StringBuffer sql = new StringBuffer("select t.* from cars_store t where 1=1 ");
		if (params != null && params.size() > 0) {
			for (String key : params.keySet()) {
				String value = (String) params.get(key);
				if (StringUtils.isNotEmpty(value)) {
					if (key.equalsIgnoreCase("tel")) {
						sql.append(" and (t.tel like '%"  + value + "%' or t.mobile like '%" + value + "%')");
					} else {
						sql.append(" and t." + key + " like '%" + value + "%'");
					}
				}
			}
		}
		SoulPage<Map<String, Object>> pageResult = storeRepository.findBySqlForSoul(page, sql.toString(), Map.class);
		return pageResult;
	}
}
